package com.illtamer.infinite.sillage.config.schedule;

import com.illtamer.infinite.sillage.entity.ViewHandler;
import com.illtamer.infinite.sillage.service.BlogService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Slf4j
@Configuration
@EnableScheduling
public class ViewCountScheduleTask {

    private ApplicationContext context;

    @Resource(name = "blogService")
    private BlogService blogService;

    @Scheduled(cron = "0 30 * * * *")
    protected void saveViews() {
        log.info("执行定时任务，刷新浏览次数");
        ViewHandler viewHandler = context.getBean(ViewHandler.class);
        viewHandler.analysis().forEach((blogId, count) -> blogService.updateViews(count, blogId));
    }

    @Bean
    public ViewHandler getViewHandler() {
        return new ViewHandler();
    }

    @Autowired
    public void setContext(ApplicationContext context) {
        this.context = context;
    }

}
